package com.boco.fznq.network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.boco.fznq.BOCOApplication;

import okhttp3.internal.Version;

/**
 * Created by jiangcheng on 2017/7/13.
 */

public class NetworkUtils {

    /**
     * 判断是否离线
     *
     * @return true则有网络, 否则离线
     */
    public static boolean isNetworkConnected() {
        NetworkInfo networkInfo = getNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }

    /**
     * 获取网络状态信息
     *
     * @return NetworkInfo
     */
    public static NetworkInfo getNetworkInfo() {
        ConnectivityManager manager = (ConnectivityManager) BOCOApplication.getContext().
                getSystemService(Context.CONNECTIVITY_SERVICE);
        return manager.getActiveNetworkInfo();
    }

    /**
     * 判断是否Wifi连线
     *
     * @return true则wifi, 否则不是
     */
    public static boolean isWifi() {
        NetworkInfo activeNetworkInfo = getNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 获取UserAgent的信息, 处理okhttp的请求头的value不能传非法字符的问题, 特别是中文字符
     *
     * @return
     */
    public static String getUserAgentInfo() {
        String deviceInfo = getDefaultUserAgent() + " " + Version.userAgent();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0, length = deviceInfo.length(); i < length; i++) {
            char c = deviceInfo.charAt(i);
            if ((c <= '\u001f' && c != '\u0009' /* htab */) || c >= '\u007f') {
                // 转为unicode码
                stringBuffer.append(String.format("\\u%04x", (int) c));
            } else {
                stringBuffer.append(c);
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 获取默认的UserAgent
     *
     * @return
     */
    public static String getDefaultUserAgent() {
        return System.getProperty("http.agent");
    }
}
